function checkBrowser() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera) {
        return "Opera"
    }
    ; //判断是否Opera浏览器
    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    } //判断是否Firefox浏览器
    if (userAgent.indexOf("Chrome") > -1) {
        return "Chrome";
    }
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    } //判断是否Safari浏览器
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
        return "IE";
    }
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        return "IE";
    }
    ; //判断是否IE浏览器
}

function appendZero(num) {
    if ((typeof num) == "string") {
        if (num.length == 1)
            return "0" + num;
        else
            return num;
    }
    else if (parseInt("" + num) < 10) {
        return "0" + parseInt(num);
    }
    else
        return num;
}

/* 将无序的角色列表重构成按照父子关系排列的数组 */
function reorderParents(list, parent, ret, parentProperty, nameProperty) {
    for (var i = 0; i < list.length; i++) {
        if (list[i][parentProperty] == "" || list[i][parentProperty] == 0)
            list[i][parentProperty] = null;

        if (list[i][parentProperty] == parent) {
            ret.push(list[i]);
            reorderParents(list, list[i][nameProperty], ret, parentProperty, nameProperty);
        }
    }
}

/* 将无序的权限列表重构成按照父子关系排列的数组 */
function reorderParentsPermission(list, parent, ret, parentProperty, nameProperty) {
    var isExit = false;
    for (var i = 0; i < list.length; i++) {
        if (!list[i][parentProperty])
            list[i][parentProperty] = null;
        if (list[i][parentProperty] === parent) {
            if (list[i]['type'] === 1) {
                isExit = true;
                ret.push(list[i]);
                continue;
            }
            isExit = reorderParentsPermission(list, list[i][nameProperty], ret, parentProperty, nameProperty);
            if (isExit) {
                ret.push(list[i]);
            }
        }
    }
    return isExit;
}

/**
 * 获取顶层窗口,用于存储一些全局变量
 * @returns {Window}
 */
function getTopWindow() {
    var ret = window.parent;
    var i = 10;
    while (i > 0) {
        if (ret === window.parent) {
            return ret;
        }
        ret = ret.parent;
        i -= 1;
    }
}

/* 用于给子页面调用,判断是否属于某个角色,多个角色用|隔开*/
function hasRoles(roles) {
    var role = getTopWindow().role;
    var roleArray = roles.replace(/ /g, '').split("|");

    if(!role)
        return null;
    for (var i = 0; i < roleArray.length; i++) {
        for (var j = 0; j < role.length; j++) {
            if (roleArray[i] == role[j]) {
                return true;
            }
        }
    }
    return false;
}

/* 判断当前用户是否具有某些权限, 多权限可以用| 隔开 */
function hasPerms(perms) {
    var permsSupported = getTopWindow().perms;
    if(!permsSupported)
        return null;
    var permsArray = perms.replace(/ /g, '').split("|");
    for (var i = 0; i < permsArray.length; i++) {
        for (var j = 0; j < permsSupported.length; j++) {
            if (permsArray[i] == permsSupported[j])
                return true;
        }
    }
    return false;
}

/* 判断前端权限是否OK */
function securityReady() {
    var role = getTopWindow().role;
    return !!role;
}

function hasPermsLanMode(){
    return getTopWindow().isLanMode;
}

/* 框架页面第一次访问时将该用户的角色信息拉取下来,保存在全局变量role中 */
function getRolesAndPermissions(callback) {
    postJsonNotLayuiLoad("/user/getRolesAndPermissions.x", null, function (data) {
        var role = data.data.role.split(",");
        var top = getTopWindow();
        top.role = role;
        top.perms = data.data.perms;
        top.isLanMode = data.data.isLanMode;
        if(callback)
            callback();
    });
}

/**
 * 清空object中所有属性并返回
 * @param object
 * @param nullKeys
 * @returns {*}
 */
function emptyObj(object, nullKeys) {
    var retObj = {};
    p: for (var key in object) {
        if (nullKeys) {
            for (var i in nullKeys) {
                if (nullKeys[i] === key) {
                    continue p;
                }
            }
        }
        retObj[key] = '';
    }
    return retObj;
}

/* JQuery query插件移植,用于获取url中的参数 */
new function (settings) {
    var $separator = settings.separator || '&';
    var $spaces = settings.spaces === false ? false : true;
    var $suffix = settings.suffix === false ? '' : '[]';
    var $prefix = settings.prefix === false ? false : true;
    var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
    var $numbers = settings.numbers === false ? false : true;

    jQuery.query = new function () {
        var is = function (o, t) {
            return o != undefined && o !== null && (!!t ? o.constructor == t : true);
        };
        var parse = function (path) {
            var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
            while (m = rx.exec(match[2])) tokens.push(m[1]);
            return [base, tokens];
        };
        var set = function (target, tokens, value) {
            var o, token = tokens.shift();
            if (typeof target != 'object') target = null;
            if (token === "") {
                if (!target) target = [];
                if (is(target, Array)) {
                    target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
                } else if (is(target, Object)) {
                    var i = 0;
                    while (target[i++] != null) ;
                    target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
                } else {
                    target = [];
                    target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
                }
            } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
                var index = parseInt(token, 10);
                if (!target) target = [];
                target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
            } else if (token) {
                var index = token.replace(/^\s*|\s*$/g, "");
                if (!target) target = {};
                if (is(target, Array)) {
                    var temp = {};
                    for (var i = 0; i < target.length; ++i) {
                        temp[i] = target[i];
                    }
                    target = temp;
                }
                target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
            } else {
                return value;
            }
            return target;
        };

        var queryObject = function (a) {
            var self = this;
            self.keys = {};

            if (a.queryObject) {
                jQuery.each(a.get(), function (key, val) {
                    self.SET(key, val);
                });
            } else {
                jQuery.each(arguments, function () {
                    var q = "" + this;
                    q = q.replace(/^[?#]/, '');
                    q = q.replace(/[;&]$/, '');
                    if ($spaces) q = q.replace(/[+]/g, ' ');

                    jQuery.each(q.split(/[&;]/), function () {
                        var key = decodeURIComponent(this.split('=')[0] || "");
                        var val = decodeURIComponent(this.split('=')[1] || "");

                        if (!key) return;

                        if ($numbers) {
                            if (/^[+-]?[0-9]+\.[0-9]*$/.test(val))
                                val = parseFloat(val);
                            else if (/^[+-]?[0-9]+$/.test(val))
                                val = parseInt(val, 10);
                        }

                        val = (!val && val !== 0) ? true : val;

                        if (val !== false && val !== true && typeof val != 'number')
                            val = val;

                        self.SET(key, val);
                    });
                });
            }
            return self;
        };

        queryObject.prototype = {
            queryObject: true,
            has: function (key, type) {
                var value = this.get(key);
                return is(value, type);
            },
            GET: function (key) {
                if (!is(key)) return this.keys;
                var parsed = parse(key), base = parsed[0], tokens = parsed[1];
                var target = this.keys[base];
                while (target != null && tokens.length != 0) {
                    target = target[tokens.shift()];
                }
                return typeof target == 'number' ? target : target || "";
            },
            get: function (key) {
                var target = this.GET(key);
                if (is(target, Object))
                    return jQuery.extend(true, {}, target);
                else if (is(target, Array))
                    return target.slice(0);
                return target;
            },
            SET: function (key, val) {
                var value = !is(val) ? null : val;
                var parsed = parse(key), base = parsed[0], tokens = parsed[1];
                var target = this.keys[base];
                this.keys[base] = set(target, tokens.slice(0), value);
                return this;
            },
            set: function (key, val) {
                return this.copy().SET(key, val);
            },
            REMOVE: function (key) {
                return this.SET(key, null).COMPACT();
            },
            remove: function (key) {
                return this.copy().REMOVE(key);
            },
            EMPTY: function () {
                var self = this;
                jQuery.each(self.keys, function (key, value) {
                    delete self.keys[key];
                });
                return self;
            },
            load: function (url) {
                var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
                var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
                return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
            },
            empty: function () {
                return this.copy().EMPTY();
            },
            copy: function () {
                return new queryObject(this);
            },
            COMPACT: function () {
                function build(orig) {
                    var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
                    if (typeof orig == 'object') {
                        function add(o, key, value) {
                            if (is(o, Array))
                                o.push(value);
                            else
                                o[key] = value;
                        }

                        jQuery.each(orig, function (key, value) {
                            if (!is(value)) return true;
                            add(obj, key, build(value));
                        });
                    }
                    return obj;
                }

                this.keys = build(this.keys);
                return this;
            },
            compact: function () {
                return this.copy().COMPACT();
            },
            toString: function () {
                var i = 0, queryString = [], chunks = [], self = this;
                var encode = function (str) {
                    str = str + "";
                    if ($spaces) str = str.replace(/ /g, "+");
                    return encodeURIComponent(str);
                };
                var addFields = function (arr, key, value) {
                    if (!is(value) || value === false) return;
                    var o = [encode(key)];
                    if (value !== true) {
                        o.push("=");
                        o.push(encode(value));
                    }
                    arr.push(o.join(""));
                };
                var build = function (obj, base) {
                    var newKey = function (key) {
                        return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
                    };
                    jQuery.each(obj, function (key, value) {
                        if (typeof value == 'object')
                            build(value, newKey(key));
                        else
                            addFields(chunks, newKey(key), value);
                    });
                };

                build(this.keys);

                if (chunks.length > 0) queryString.push($hash);
                queryString.push(chunks.join($separator));

                return queryString.join("");
            }
        };

        return new queryObject(location.search, location.hash);
    };
}(jQuery.query || {});


